<?php
declare (strict_types=1);

namespace app\common\model;

use think\Model;
use think\facade\Db;

class Statistics extends Model
{
    public static function _update($key, $amount): void
    {
        parent::where('key', $key)
            ->inc('today', floatval($amount))
            ->inc('week', floatval($amount))
            ->inc('month', floatval($amount))
            ->inc('year', floatval($amount))
            ->inc('sum', floatval($amount))
            ->save();
    }

    /**
     * 更新统计
     * 定时
     */
    public static function _timing(): array
    {
        parent::startTrans();
        try {
            $m = date('m');
            $d = date('d');
            $w = date('w');
            $sql = '`yesterday` = `today`, `today` = 0';
            if ($w == '1') {
                $sql .= ', `last_week` = `week`, `week` = 0';
            }
            if ($d == '01') {
                $sql .= ', `last_month` = `month`, `month` = 0';
                if ($m == '01') {
                    $sql .= ', `last_year` = `year`, `year` = 0';
                }
            }
            Db::execute('update `statistics` set ' . $sql);
            Db::execute('update `user` set `always_day` = 0 where `is_day_sign` = 0');
            Db::execute('update `user` set `is_day_sign` = 0 where `is_day_sign` = 1');
            OrderTemporary::autoReceipt();
            parent::commit();

            return ['code' => 1, 'msg' => '更新成功'];
        } catch (\Exception $e) {
            parent::rollback();
            Logs::write('logs/statistics.log', $e->getMessage());

            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}